package com.base.hong.widget

import android.content.Context
import android.content.res.Resources
import android.util.AttributeSet
import android.util.TypedValue
import android.view.View
import android.view.ViewGroup


/**
 * @ClassName FlowLayout
 * @Description TODO
 * @Author Hong
 * @Date 2022/10/11 14:52
 * @Version 1.0
 */
class FlowLayoutView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : ViewGroup(context, attrs, defStyleAttr) {


    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        //度量子view
        var childCount = childCount
        var lineViews = arrayListOf<View>()
        var mLineWidth = 0
        var mLineHeight = 0
        for (i in 0 until childCount) {
            val childView = getChildAt(i)
            val childLP = childView.layoutParams

            val childWidthMeasureSpec =
                getChildMeasureSpec(widthMeasureSpec, paddingLeft + paddingRight, childLP.width)

            val childHeightMeasureSpec =
                getChildMeasureSpec(heightMeasureSpec, paddingTop + paddingBottom, childLP.height)

            childView.measure(childWidthMeasureSpec, childHeightMeasureSpec)
            //获取子view 的宽高
            val childMeasureWidth = childView.measuredWidth
            val childMeasureHeight = childView.measuredHeight
            lineViews.add(childView)

            mLineWidth += childMeasureWidth + dp2px(8)
            mLineHeight = mLineHeight.coerceAtLeast(childMeasureHeight)


        }
    }

    override fun onLayout(p0: Boolean, p1: Int, p2: Int, p3: Int, p4: Int) {


    }

    private fun dp2px(dp: Int): Int {
        return TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP,
            dp.toFloat(),
            Resources.getSystem().displayMetrics
        ).toInt()
    }
}